package com.mycompany.sigemp.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mycompany.sigemp.model.Usuario;
import com.mycompany.sigemp.service.UsuarioService;

@Controller
public class UsuarioController {
	@Autowired
	UsuarioService uService;
	
	private static Log logger = LogFactory.getLog(UsuarioController.class);
	
	@RequestMapping(value="/perfil.htm",method=RequestMethod.POST)
	public String procesarPerfil(@RequestParam String selectCargo,String txtUsuario, 
			                     HttpServletRequest request, HttpSession session, String txtClave,
			                     Model model){
		String vista = "sigemp";
		if(selectCargo.equals("Seleccione") || txtUsuario.equals("") || txtClave.equals("")){
			return "sigemp";
		}
		Usuario user = uService.validarUsuario(txtUsuario, txtClave); 
		if(user==null){
			return "sigemp";
		}
		if(user.getAcceso().equals(selectCargo)){
			HttpSession nSession = request.getSession(); 
		    nSession = request.getSession(true);
			if(user.getAcceso().equals("Administrador")){				
			    nSession.setAttribute("user", user.getNombre()); 
			    logger.debug("Entro a perfil del usuario : "+ user.getNombre());
				vista = "viewAdministrador";
			}
			if(user.getAcceso().equals("Operario")){
		        nSession.setAttribute("user", user.getNombre()); 
		        logger.debug("Entro a perfil del usuario : "+ user.getNombre());
				vista = "home";
			}
		}
		return vista;
	}
	
	@RequestMapping(value="/salir.htm")
	public String vistaInicio(HttpServletRequest request, HttpSession session){
		session = request.getSession(); 
        session.invalidate(); 
		return "sigemp";
	}

}
